// BTGUID for the installation, necessary to get the extension directory
var BTGUID="firefoxbtclient@chad.crabtree"
//the BT server process
var process=null;
var RUNNING=false;
//I don't currently use this, but I can imagine a day I might want it
var windows=[];
// PORT # for the http bt server this
// will be randomly determined and then set
// when the server is launched
var PORT=8080;
//torrent_keys is a temporary global var
//used for queueing torrents for download
//it is almost always empty (99.99%)
var torrent_keys=[];
//statuses is a bookeeping hash for the running and
//paused torrents
var statuses={'paused':{},'running':{}}
var firefoxbtclient = {
  onLoad: function() {
    // initialization code
    this.initialized = true;
    this.strings = document.getElementById("firefoxbtclient-strings");
    document.getElementById("contentAreaContextMenu")
            .addEventListener("popupshowing", function(e) { firefoxbtclient.showContextMenu(e); }, false);
    loadState();
    
  },
  unLoad: function(e) {
    saveState();
    if (process) {
        get_url="http://localhost:"+PORT+"/stop";
        var req = new XMLHttpRequest();
        req.open('GET', get_url, false); 
        req.send(null);
        process.kill();
    }
  },
  showContextMenu: function(event) {
    var element = document.popupNode;
    menu=document.getElementById("context-firefoxbtclient");
    if (element.href) {
        menu.style.display="block";
    }
    else {
        menu.style.display='none';
    }
  },
  onContextMenu: function (e) {
    firefoxbtclient.doMagic(gContextMenu);

  },
  onMenuItemCommand: function(e) {
    alert('MenuItemCommand');
  },
  onToolbarButtonCommand: function(e) {
    alert('toolbar');
  },
  doMagic: function(e) {
    var torrent_info=checkForTorrentFile(e)
    if (torrent_info) {
        //store torrent info for later server init
        torrent_keys.push(torrent_info);
        launchBTServer();
      }
  },
}

function attach_globals_to_window(win) {
    win.BTGUID="firefoxbtclient@chad.crabtree"
    win.RUNNING=false;
    win.PORT=8080;
    win.torrent_keys=torrent_keys;
    win.statuses=statuses;
    windows.push(win);
}
function saveState() {
    state=statuses.toJSONString();
    state_file=getPrefDir()
    state_file.append('btclientstate.jsn');
    var foStream = Components.classes["@mozilla.org/network/file-output-stream;1"]
        .createInstance(Components.interfaces.nsIFileOutputStream);
    foStream.init(state_file, 0x02 | 0x08 | 0x20, 0666, 0); 
    foStream.write(state, state.length);
    foStream.close();
}
function loadState() {
    state_file=getPrefDir()
    state_file.append('btclientstate.jsn');
    var data = "";
    var fstream = Components.classes["@mozilla.org/network/file-input-stream;1"]
        .createInstance(Components.interfaces.nsIFileInputStream);
    var sstream = Components.classes["@mozilla.org/scriptableinputstream;1"]
        .createInstance(Components.interfaces.nsIScriptableInputStream);
    fstream.init(state_file, -1, 0, 0);
    sstream.init(fstream); 

    var str = sstream.read(4096);
    while (str.length > 0) {
        data += str;
        str = sstream.read(4096);
    }

    sstream.close();
    fstream.close();
    statuses=data.parseJSON();
    if (statuses['running']) {
        count=0;
        for (var k in statuses['running']) {
            if (k!="toJSONString") {
                torrent_keys[count]=statuses['running'][k];
                count+=1;
            }
        }
        setTimeout('launchBTServer();',5000);
    }

}
window.addEventListener("load", function(e) { firefoxbtclient.onLoad(e); }, false);
window.addEventListener("unload", function(e) { firefoxbtclient.unLoad(e); }, false);
